package com.msite.filter

import com.msite.mapper.SysPermMapper
import com.msite.model.SysPerm

import javax.annotation.Resource
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 * Created by tpeng on 2015/12/4.
 */
class PermFilter implements Filter{
    /**
     * key: SysPerm的url   value=SysPerm
     */
    private static def PermMap = new HashMap<String, SysPerm>();

    @Resource
    SysPermMapper sysPermMapper;

    @Override
    void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;
       /* Subject subject = SecurityUtils.getSubject()
        if(!subject || !subject.authenticated){
            chain.doFilter(request, response)
            return;
        }
        def isAjax = httpRequest.requestURI.endsWith(".json");
        def perm;
        if(PermMap.containsKey(httpRequest.requestURI)){
            perm = PermMap.get(httpRequest.requestURI)
        }else{
            perm = sysPermMapper.getByPUrl(httpRequest.requestURI)
        }
       //println this.class.toString()+"------"+httpRequest.requestURI+"----------isAjax:"+isAjax

        if(perm){
            PermMap.put(perm.purl, perm);
            if(!subject.isPermitted(perm.key)){
                if(!isAjax){
                    httpResponse.sendRedirect("/noperm_")
                }else {
                    httpResponse.writer.write(JSONObject.toJSON(new JsonResult(
                            code: JsonResult.CODE_NO_PERM,
                            msg: "Sorry!没有操作权限!"
                    )))
                    httpResponse.writer.flush()
                    httpResponse.writer.close()
                }
                return;
            }
        }*/
        chain.doFilter(request, response)
    }

    @Override
    void destroy() {

    }
}
